// 非标结构件表单组件 - 用于新增/编辑/查看非标结构件信息
<script setup lang="ts">
// 导入所需的Vue组件和工具函数
import { ref, reactive, defineProps, defineEmits, watch, computed, onMounted, onBeforeUnmount, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { Money, Box, Van, SetUp, More, Plus, Delete, Close, View, ArrowUp, ArrowDown, DCaret } from '@element-plus/icons-vue'
import useDialog from '@/hooks/useDialog'

// 导入相关类型定义和API
import { Quotation, QuotationListParam } from '@/api/quotation/type.ts'
import {
  getListApi,
  getBOMList,
  getDetailByIdApi,
  addApi,
  editApi,
} from '@/api/quotation/index.ts'

// 导入规格配置详情API
import { specificationDetailQuery } from '@/api/specificationDetail/type.ts'
import { getSpecificationDetailApi } from '@/api/specificationDetail/index.ts'

// 导入物料档案相关API
import { Material, MaterialListParam } from '@/api/material/type.ts'
import { getListApi as getMaterialListApi, getMaterialDetialApi } from '@/api/material/index.ts'

// 导入项目相关API
import { ProjectDocument, ProjectDocumentListParam } from "@/api/project/type.ts"
import { getProjectDocumentListApi } from "@/api/project"

// 导入物料选择器组件
import MaterialDialog from '@/views/baseInfo/material/materialDialog/index.vue'

// 导入颜色和项目选择器相关
import { getListApi as getColorListApi } from '@/api/color'
import type { Color } from '@/api/color/type'
import SysDialog from '@/components/dialog/SysDialog.vue'
import ArchiveSelector from '@/components/common/ArchiveSelector.vue'

// 引入统一格式化工具
import { formatPrice, formatNumber } from '@/utils/formatter'

// 定义组件属性
const props = defineProps<{
  Id?: number //  ID，编辑时传入
  mode: string // 组件模式：add/edit/view
}>()

// 定义组件事件
const emit = defineEmits(['save-success', 'cancel'])

// 表单ref，用于表单验证
const formRef = ref<FormInstance>()

// 使用dialog钩子获取弹窗控制方法
const { dialog, onShow, onClose } = useDialog()

// 初始化表单数据
const formData = reactive<Quotation>({
  id: undefined, // 报价单ID
  parentId: undefined, // 父报价单ID（如果有的话）
  name: undefined, // 名称
  specification: undefined, // 规格
  material: undefined, // 材质
  width: undefined, // 宽度
  height: undefined, // 高度
  quantity: undefined, // 数量
  unit: undefined, // 单位，如"个"、"米"、"箱"等
  color: undefined, // 颜色
  colorPrice: 0,
  remark: undefined, // 备注
  unitPrice: undefined, // 含税单价
  unitWeight: undefined, // 单重
  kgPrice: undefined, // 公斤价
  totalPrice: undefined, // 总价
  totalWeight: undefined, // 总重
  projectId: undefined, // 客户
  projectName: undefined, // 客户
  packingPrice: undefined,  // 包装费
  transportationPrice:  undefined,  // 运输费
  implementationPrice:  undefined,  // 实施费
  otherPrice:  undefined, // 其他费用
  packingPriceCoefficient: undefined, // 包装费系数
  materialModel: undefined,
  remark1: undefined,
  remark2: undefined,
  remark3: undefined,
  fastenerType: undefined,
  activate: undefined, // 激活状态
  detailMap: undefined, // 费用详情数据(JSON字符串)
  map: undefined, // 解析后的费用详情数据
  children: [], // 空数组初始化  计件产品配置
})

// 保存从后端获取的原始数据，用于包装费计算
const originalUnitPrice = ref<number>(0)
const originalTotalPrice = ref<number>(0)

// 项目选择相关
const selectedProject = ref<ProjectDocument | null>(null)
const projectList = ref<ProjectDocument[]>([])

// 物料选择相关
const materialDialogRef = ref()
const selectedMaterials = ref<Material[]>([])

// 颜色选择器相关
const colorSelectorVisible = ref(false)
const selectedColor = ref<Color>()

// 项目选择器相关
const projectSelectorVisible = ref(false)

// 当前激活的tab页
const activeTab = ref('materials')

// 定义详情数据的接口
interface DetailData {
  [key: string]: number | string
}

// 当前显示的详情数据
const currentDetailData = ref<DetailData | null>(null)

// 表单校验规则
const rules = {
  name: [{required: true, message: '请输入名称', trigger: 'change'}],
  color: [{required: true, message: '请选择颜色', trigger: 'change'}],
  projectName: [{required: true, message: '请选择项目'}],
}

// 提交表单
const submitForm = async () => {
  if (props.mode === 'view') return // 查看模式不允许提交
  try {
    // 表单验证
    await formRef.value?.validate()
    
    // 在保存前，确保所有计算字段都是最新的
    if (formData.children && formData.children.length > 0) {
      calculateTotalPrice()
    }
    
    // 在保存前，将children中的map数据序列化并保存到detailMap字段
    if (formData.children && formData.children.length > 0) {
      formData.children.forEach((child: any) => {
        // 将物料的totalPrice赋值给unitPrice
        child.unitPrice = child.totalPrice
        
        if (child.map && Object.keys(child.map).length > 0) {
          // 将map数据序列化为JSON字符串保存到detailMap字段
          child.detailMap = JSON.stringify(child.map)
        }
      })
    }
    
    console.log(props.mode + '提交数据：', formData)
    if (props.mode === 'add') {
      // 调用保存API
      await addApi(formData)
    }
    if (props.mode === 'edit') {
      // 调用保存API
      await editApi(formData)
    }
    ElMessage.success('保存成功')
    emit('save-success')
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('保存失败')
  }
}

function printPage() {
  window.print();
}

// 取消操作
const cancel = () => {
  emit('cancel')
}

// 计算包装费并更新最终总价  
const calculateFinalPrice = () => {
  if (!originalTotalPrice.value || !formData.totalWeight) {
    return
  }
  
  // 原始总价（基础总价 × 数量）
  const originalPrice = originalTotalPrice.value
  // 总重量
  const totalWeight = Number(formData.totalWeight) || 0
  // 包装费系数
  const packingCoefficient = Number(formData.packingPriceCoefficient) || 0
  
  // 计算包装费：总重 × 包装费系数
  const packingFee = totalWeight * packingCoefficient
  
  // 其他费用
  const colorPrice = Number(formData.colorPrice) || 0
  const transportationPrice = Number(formData.transportationPrice) || 0
  const implementationPrice = Number(formData.implementationPrice) || 0
  const otherPrice = Number(formData.otherPrice) || 0
  
  // 最终总价 = 原始总价 + 颜色价格 + 运输费 + 实施费 + 其他费用 + 包装费
  const finalTotalPrice = originalPrice + colorPrice + transportationPrice + implementationPrice + otherPrice + packingFee
  
  // 更新总价
  formData.totalPrice = Number(finalTotalPrice.toFixed(2))
}

// 监听包装费系数变化，自动重新计算总价
watch(
  () => formData.packingPriceCoefficient,
  (newVal) => {
    if (newVal !== undefined && formData.children && formData.children.length > 0) {
      calculateTotalPrice()
    }
  }
)

// 防抖函数用于计算总价
let calculateTotalPriceTimeout: NodeJS.Timeout | null = null
const debouncedCalculateTotalPrice = () => {
  if (calculateTotalPriceTimeout) {
    clearTimeout(calculateTotalPriceTimeout)
  }
  calculateTotalPriceTimeout = setTimeout(() => {
    try {
      calculateTotalPrice()
    } catch (error) {
      console.error('防抖计算总价失败:', error)
    }
  }, 100) // 100ms防抖
}

// 监听物料清单变化，自动重新计算基础数据 - 优化版本
watch(
  () => formData.children,
  (newChildren, oldChildren) => {
    // 在拖拽过程中避免触发计算
    if (dragState.isDragging) {
      console.log('拖拽进行中，跳过总价计算')
      return
    }
    
    // 确保新数据是有效的数组
    if (!newChildren || !Array.isArray(newChildren)) {
      console.log('children数据无效，跳过总价计算')
      return
    }
    
    // 防抖计算，避免频繁触发
    debouncedCalculateTotalPrice()
  },
  { deep: true }
)

// 专门监听数量变化，确保总价正确更新 - 新增强制计算逻辑
watch(
  () => formData.quantity,
  (newQuantity, oldQuantity) => {
    // 避免初始化时的无效触发
    if (newQuantity === oldQuantity || !newQuantity || newQuantity <= 0) {
      return
    }
    
    console.log('主数量变化:', { from: oldQuantity, to: newQuantity })
    
    // 强制重新计算，不受拖拽状态影响
    try {
      calculateTotalPrice()
      console.log('主数量变化后计算完成:', {
        quantity: newQuantity,
        unitPrice: formData.unitPrice,
        totalPrice: formData.totalPrice,
        totalWeight: formData.totalWeight
      })
    } catch (error) {
      console.error('主数量变化计算失败:', error)
    }
  }
)

// 计算当前包装费（用于显示）
const currentPackingFee = computed(() => {
  const totalWeight = Number(formData.totalWeight) || 0
  const packingCoefficient = Number(formData.packingPriceCoefficient) || 0
  return totalWeight * packingCoefficient
})

// 计算物料清单的总单价（所有物料的总价）
const calculateTotalUnitPrice = () => {
  let totalPrice = 0
  formData.children.forEach((child: any) => {
    totalPrice += Number(child.totalPrice) || 0
  })
  return totalPrice
}

// 计算物料清单的总单重（所有物料的总重）
const calculateTotalUnitWeight = () => {
  let totalWeight = 0
  formData.children.forEach((child: any) => {
    totalWeight += Number(child.totalWeight) || 0
  })
  return totalWeight
}

// 计算公斤价（总价/总重）
const calculateKgPrice = () => {
  const totalPrice = calculateTotalUnitPrice()
  const totalWeight = calculateTotalUnitWeight()
  if (totalWeight > 0) {
    return totalPrice / totalWeight
  }
  return 0
}

// 计算最终总重（单重 × 数量）
const calculateFinalTotalWeight = () => {
  const unitWeight = calculateTotalUnitWeight()
  const quantity = Number(formData.quantity) || 0
  return unitWeight * quantity
}

// 计算最终总价（包含所有费用）
const calculateFinalTotalPrice = () => {
  const basePrice = calculateTotalUnitPrice() * (Number(formData.quantity) || 0)
  const colorPrice = Number(formData.colorPrice) || 0
  const transportationPrice = Number(formData.transportationPrice) || 0
  const implementationPrice = Number(formData.implementationPrice) || 0
  const otherPrice = Number(formData.otherPrice) || 0
  
  // 包装费 = 总重 × 包装费系数
  const totalWeight = calculateFinalTotalWeight()
  const packingCoefficient = Number(formData.packingPriceCoefficient) || 0
  const packingFee = totalWeight * packingCoefficient
  
  return basePrice + colorPrice + transportationPrice + implementationPrice + otherPrice + packingFee
}

// 监听bomId变化,当编辑时加载BOM详情
watch(
  () => props.Id,
  async (newVal) => {
    console.log(props.Id)
    if (newVal) {
      try {
        const res = await getDetailByIdApi(newVal)
        formData.materialModel=res.data.specification
        console.log(res.data)
        if (res?.data) {
          Object.assign(formData, res.data) // 加载详情数据到表单
          selectedProject.value = {
            id: res.data.projectId,
            name: res.data.projectName || '',
          } as ProjectDocument
          
          // 处理children数据（如果存在）
          if (res.data.children && res.data.children.length > 0) {
            formData.children = res.data.children.map((item: any, index: number) => ({
              id: item.id,
              tempId: item.id ? `exist_${item.id}` : `temp_${Date.now()}_${index}`, // 为每个项目生成唯一key
              parentId: item.parentId,
              name: item.name,
              materialModel: item.materialModel,
              specification: item.specification,
              material: item.material,
              height: item.height,
              width: item.width,
              quantity: item.quantity,
              unitPrice: item.unitPrice,
              unitWeight: item.unitWeight,
              kgPrice: item.kgPrice,
              totalPrice: item.totalPrice,
              totalWeight: item.totalWeight,
              // 优先使用保存的detailMap数据，如果没有则使用map字段
              map: item.detailMap ? JSON.parse(item.detailMap) : (item.map || {}),
              detailMap: item.detailMap, // 保存原始的JSON字符串
            }))
          }
          
          // 保存原始数据用于包装费计算
          originalUnitPrice.value = Number(res.data.unitPrice) || 0
          
          // 计算原始总价（从数据库加载时，需要减去包装费）
          const totalPrice = Number(res.data.totalPrice) || 0
          const totalWeight = Number(res.data.totalWeight) || 0
          const packingCoefficient = Number(res.data.packingPriceCoefficient) || 0
          const packingFee = totalWeight * packingCoefficient
          originalTotalPrice.value = totalPrice - packingFee
          
          // 数据加载完成后初始化拖拽事件
          if (props.mode !== 'view') {
            setTimeout(async () => {
              await initTableDragEvents()
            }, 300)
          }
        }
      } catch (error) {
        console.error('获取详情失败:', error)
        ElMessage.error('获取详情失败')
      }
    }
  },
  { immediate: true }
)

// 获取项目列表
const loadProjectList = async () => {
  try {
    const res = await getProjectDocumentListApi({ 
      page: 1, 
      limit: 1000,
      name: undefined,
      code: undefined,
      customer: undefined,
      status: undefined
    })
    if (res && res.data) {
      projectList.value = res.data.list || []
    }
  } catch (error) {
    console.error('获取项目列表失败:', error)
  }
}

// 处理项目选择
const handleProjectChange = (projectId: number) => {
  const project = projectList.value.find(p => p.id === projectId)
  if (project) {
    selectedProject.value = project
    formData.projectName = project.name
  }
}

// 打开物料选择器
const openMaterialSelector = () => {
  // 规格配置详情模块允许重复选择同一个物料，所以不传递已选择的物料列表
  // 这样物料选择器就不会对已选择的物料进行去重或禁用处理
  console.log('打开物料选择器，允许重复选择物料')
  materialDialogRef.value?.onShow([])
}

// 处理物料选择变化
const handleMaterialSelectionChange = (selection: Material[]) => {
  console.log('物料选择变化：', selection)
  selectedMaterials.value = selection
}

// 确认物料选择
const confirmMaterialSelect = async () => {
  if (selectedMaterials.value.length === 0) {
    ElMessage.warning('请至少选择一个物料')
    return
  }
  
  console.log('确认选择物料：', selectedMaterials.value)
  
  // 将选中的物料转换为children格式，并通过后端接口计算价格
  const childrenPromises = selectedMaterials.value.map(async (material: Material) => {
    // 构建查询参数，调用getMaterialDetial接口
    // 使用物料原本的信息，而不是可能被修改过的值
    const queryParams: Material = {
      id: material.id,
      materialName: material.materialName || '',
      materialModel: material.materialModel || '',
      materialType: material.materialType || '',
      length: material.length || 0,
      breadth: material.breadth || 0,
      number: material.number || 1,
      // 使用物料原本的信息
      unitWeight: material.unitWeight || 0,
      purchasePrice: material.purchasePrice || 0,
      unitArea: material.unitArea || 0,
      // 保存完整的物料信息
      materialCode: material.materialCode,
      categoryId: material.categoryId,
      categoryName: material.categoryName,
      unitId: material.unitId,
      unitName: material.unitName,
      specification: material.specification,
      specificationTwo: material.specificationTwo,
      brand: material.brand,
      manufacturer: material.manufacturer,
      price: material.price,
      totalArea: material.totalArea,
      totalWeight: material.totalWeight,
      thickness: material.thickness,
      weldingLength: material.weldingLength,
      imageUrl: material.imageUrl,
      process: material.process,
      mileagePrice: material.mileagePrice,
      unitPriceCoefficient: material.unitPriceCoefficient,
      materialRequisitionCoefficient: material.materialRequisitionCoefficient,
      isActive: material.isActive,
      createTime: material.createTime,
      updateTime: material.updateTime,
    }
    
    try {
      // 调用getMaterialDetial接口获取详细信息
      const res = await getMaterialDetialApi(queryParams)
      if (res?.data) {
        return {
          id: undefined, // 不保留原始ID，避免ID冲突
          tempId: `material_${material.id}_${Date.now()}`, // 临时ID，用于拖拽排序
          materialId: material.id, // 保存原始物料ID用于回显
          parentId: undefined,
          name: material.categoryName || material.materialName || '', // 优先使用分类名称
          materialModel: material.materialModel || '',
          specification: material.materialModel || material.specification || '', // 将materialModel赋值给specification
          material: material.materialType || '',
          height: material.length || 0,
          width: material.breadth || 0,
          quantity: 1,
          unit: '个',
          unitPrice: res.data.price || material.purchasePrice || 0,
          unitWeight: res.data.totalWeight || material.unitWeight || 0,
          kgPrice: (res.data.price || material.purchasePrice || 0) / (res.data.totalWeight || material.unitWeight || 1),
          totalPrice: res.data.price || material.purchasePrice || 0,
          totalWeight: res.data.totalWeight || material.unitWeight || 0,
          map: res.data.detial || {}
        }
      } else {
        // 如果后端接口没有返回数据，使用物料档案的基础数据
        return {
          id: undefined, // 不保留原始ID，避免ID冲突
          tempId: `material_${material.id}_${Date.now()}_fallback`, // 临时ID，用于拖拽排序
          materialId: material.id, // 保存原始物料ID用于回显
          parentId: undefined,
          name: material.categoryName || material.materialName || '', // 优先使用分类名称
          materialModel: material.materialModel || '',
          specification: material.materialModel || material.specification || '', // 将materialModel赋值给specification
          material: material.materialType || '',
          height: material.length || 0,
          width: material.breadth || 0,
          quantity: 1,
          unit: '个',
          unitPrice: material.purchasePrice || 0,
          unitWeight: material.unitWeight || 0,
          kgPrice: (material.purchasePrice || 0) / (material.unitWeight || 1),
          totalPrice: material.purchasePrice || 0,
          totalWeight: material.unitWeight || 0,
          map: {}
        }
      }
    } catch (error) {
      console.error('计算物料价格失败:', error)
      // 如果计算失败，使用物料档案的基础数据
      return {
        id: undefined, // 不保留原始ID，避免ID冲突
        tempId: `material_${material.id}_${Date.now()}_error`, // 临时ID，用于拖拽排序
        materialId: material.id, // 保存原始物料ID用于回显
        parentId: undefined,
        name: material.categoryName || material.materialName || '', // 优先使用分类名称
        materialModel: material.materialModel || '',
        specification: material.materialModel || material.specification || '', // 将materialModel赋值给specification
        material: material.materialType || '',
        height: material.length || 0,
        width: material.breadth || 0,
        quantity: 1,
        unit: '个',
        unitPrice: material.purchasePrice || 0,
        unitWeight: material.unitWeight || 0,
        kgPrice: (material.purchasePrice || 0) / (material.unitWeight || 1),
        totalPrice: material.purchasePrice || 0,
        totalWeight: material.unitWeight || 0,
        map: {}
      }
    }
  })
  
  // 等待所有价格计算完成
  const newChildren = await Promise.all(childrenPromises)
  
  // 为新添加的children生成唯一的key
  newChildren.forEach((child, index) => {
    child.tempId = `temp_${Date.now()}_${index}`
  })
  
  // 规格配置详情模块支持重复选择同一物料，所以要追加而不是覆盖
  formData.children.push(...newChildren)
  
  console.log('新增的children数据：', newChildren)
  console.log('合并后的全部children数据：', formData.children)
  
  // 计算总价和总重
  calculateTotalPrice()
  
  // 重新初始化拖拽事件
  if (props.mode !== 'view') {
    setTimeout(async () => {
      await initTableDragEvents()
    }, 200)
  }
  
  ElMessage.success(`已添加 ${selectedMaterials.value.length} 个物料到清单`)
  materialDialogRef.value?.onClose()
}

// 计算总价和总重（汇总各物料的数据，不进行前端计算）- 增强版本
const calculateTotalPrice = () => {
  try {
    console.log('开始计算总价，当前children数量:', formData.children?.length || 0)
    
    let baseTotalPrice = 0
    let baseTotalWeight = 0
    
    // 确保children数组存在且有效
    if (!formData.children || !Array.isArray(formData.children)) {
      console.warn('formData.children 不是有效数组，重置为空数组')
      formData.children = []
      // 重置相关字段
      formData.unitPrice = 0
      formData.unitWeight = 0
      formData.kgPrice = 0
      formData.totalWeight = 0
      formData.totalPrice = 0
      return
    }
    
    // 如果没有物料，重置价格相关字段
    if (formData.children.length === 0) {
      console.log('物料清单为空，重置价格字段')
      formData.unitPrice = 0
      formData.unitWeight = 0
      formData.kgPrice = 0
      formData.totalWeight = 0
      formData.totalPrice = 0
      return
    }
    
    // 遍历计算物料总价和总重
    formData.children.forEach((child: any, index: number) => {
      // 检查child对象是否存在
      if (!child) {
        console.warn(`child对象为空，索引: ${index}`)
        return
      }
      
      const childUnitPrice = Number(child.unitPrice) || 0
      const childUnitWeight = Number(child.unitWeight) || 0
      
      baseTotalPrice += childUnitPrice
      baseTotalWeight += childUnitWeight
      
      console.log(`物料 ${index + 1}: ${child.name}, 单价: ${childUnitPrice}, 单重: ${childUnitWeight}`)
    })
    
    console.log('物料汇总结果:', { baseTotalPrice, baseTotalWeight })
    
    // 更新formData中的基础数据
    formData.unitPrice = Number(baseTotalPrice.toFixed(6))  // 含税单价 = 物料清单总价
    formData.unitWeight = Number(baseTotalWeight.toFixed(6)) // 单重 = 物料清单总重
    
    // 计算公斤价（含税单价/单重）
    if (baseTotalWeight > 0) {
      formData.kgPrice = Number((baseTotalPrice / baseTotalWeight).toFixed(6))
    } else {
      formData.kgPrice = 0
    }
    
    // 计算最终总重（单重 × 数量）
    const quantity = Number(formData.quantity) || 0
    formData.totalWeight = Number((baseTotalWeight * quantity).toFixed(6))
    
    // 计算最终总价（包含所有费用）
    const colorPrice = Number(formData.colorPrice) || 0
    const transportationPrice = Number(formData.transportationPrice) || 0
    const implementationPrice = Number(formData.implementationPrice) || 0
    const otherPrice = Number(formData.otherPrice) || 0
    
    // 包装费 = 总重 × 包装费系数
    const packingCoefficient = Number(formData.packingPriceCoefficient) || 0
    const packingFee = formData.totalWeight * packingCoefficient
    
    // 最终总价 = (含税单价 × 数量) + 颜色价格 + 运输费 + 实施费 + 其他费用 + 包装费
    const finalTotalPrice = (baseTotalPrice * quantity) + colorPrice + transportationPrice + implementationPrice + otherPrice + packingFee
    formData.totalPrice = Number(finalTotalPrice.toFixed(2))
    
    // 保存原始数据用于包装费计算
    originalTotalPrice.value = Number((baseTotalPrice * quantity).toFixed(6))
    
    console.log('总价计算完成:', {
      quantity,
      unitPrice: formData.unitPrice,
      unitWeight: formData.unitWeight,
      totalWeight: formData.totalWeight,
      totalPrice: formData.totalPrice,
      packingFee: packingFee.toFixed(2)
    })
    
  } catch (error) {
    console.error('计算总价时发生错误:', error)
    // 发生错误时不改变原有数据，避免界面异常
  }
}

// 删除子物料
const removeChild = (index: number) => {
  const removedChild = formData.children[index]
  console.log('删除子物料：', removedChild)
  
  // 从formData.children中删除
  formData.children.splice(index, 1)
  
  // 重新计算总价和总重
  calculateTotalPrice()
  
  console.log('删除后的children：', formData.children)
}

// 子物料数量变化 - 增强版本
const handleChildQuantityChange = async (index: number) => {
  console.log(`子物料 ${index} 数量变化开始`)
  const child = formData.children[index]
  if (!child) {
    console.warn(`子物料 ${index} 不存在`)
    return
  }
  
  if (props.mode === 'view') {
    console.log('查看模式，跳过子物料数量变化处理')
    return
  }
  
  try {
    const newQuantity = Number(child.quantity) || 1
    console.log(`子物料 ${child.name} 数量变为: ${newQuantity}`)
    
    // 构建查询参数
    const queryParams: Material = {
      id: child.materialId || child.id, // 优先使用materialId
      materialName: child.name || '',
      materialModel: child.specification || '',
      materialType: child.material || '',
      length: Number(child.height) || 0,
      breadth: Number(child.width) || 0,
      number: newQuantity,
      unitWeight: child.unitWeight || 0,
      purchasePrice: child.unitPrice || 0,
      unitArea: 0,
      materialCode: undefined,
      categoryId: undefined,
      categoryName: undefined,
      unitId: undefined,
      unitName: undefined,
      specification: child.specification,
      specificationTwo: undefined,
      brand: undefined,
      manufacturer: undefined,
      price: undefined,
      totalArea: undefined,
      totalWeight: undefined,
      thickness: undefined,
      weldingLength: undefined,
      imageUrl: undefined,
      process: undefined,
      mileagePrice: undefined,
      unitPriceCoefficient: undefined,
      materialRequisitionCoefficient: undefined,
      isActive: undefined,
      createTime: undefined,
      updateTime: undefined,
    }
    
    const res = await getMaterialDetialApi(queryParams)
    if (res?.data) {
      console.log(`子物料 ${child.name} 后端计算结果:`, res.data)
      // 直接使用后端返回的价格和重量信息，不进行前端计算
      child.unitPrice = res.data.price || child.unitPrice
      child.unitWeight = res.data.totalWeight || child.unitWeight
      child.kgPrice = (res.data.price || child.unitPrice) / (res.data.totalWeight || child.unitWeight || 1)
      child.totalPrice = res.data.price || child.unitPrice // 后端返回的就是总价
      child.totalWeight = res.data.totalWeight || child.unitWeight // 后端返回的就是总重
      child.map = res.data.detial || child.map
      
      console.log(`子物料 ${child.name} 更新后:`, {
        quantity: child.quantity,
        unitPrice: child.unitPrice,
        unitWeight: child.unitWeight,
        totalPrice: child.totalPrice,
        totalWeight: child.totalWeight
      })
      
      // 强制重新计算整体总价和总重
      calculateTotalPrice()
    } else {
      console.warn(`子物料 ${child.name} 后端未返回计算结果，保持原有数据`)
    }
  } catch (error) {
    console.error(`子物料 ${index} 重新计算价格失败:`, error)
    // 如果计算失败，至少要重新计算一次总价，使用现有数据
    try {
      calculateTotalPrice()
    } catch (calcError) {
      console.error('强制计算总价失败:', calcError)
    }
  }
}

// 子物料高度变化 - 重新计算价格
const handleChildHeightChange = async (index: number) => {
  const child = formData.children[index]
  if (child && props.mode !== 'view') {
    try {
      // 构建查询参数
      const queryParams: Material = {
        id: child.id,
        materialName: child.name || '',
        materialModel: child.specification || '',
        materialType: child.material || '',
        length: Number(child.height) || 0,
        breadth: Number(child.width) || 0,
        number: Number(child.quantity) || 1,
        unitWeight: child.unitWeight || 0,
        purchasePrice: child.unitPrice || 0,
        unitArea: 0,
        materialCode: undefined,
        categoryId: undefined,
        categoryName: undefined,
        unitId: undefined,
        unitName: undefined,
        specification: child.specification,
        specificationTwo: undefined,
        brand: undefined,
        manufacturer: undefined,
        price: undefined,
        totalArea: undefined,
        totalWeight: undefined,
        thickness: undefined,
        weldingLength: undefined,
        imageUrl: undefined,
        process: undefined,
        mileagePrice: undefined,
        unitPriceCoefficient: undefined,
        materialRequisitionCoefficient: undefined,
        isActive: undefined,
        createTime: undefined,
        updateTime: undefined,
      }
      
      const res = await getMaterialDetialApi(queryParams)
      if (res?.data) {
        // 更新价格和重量信息
        child.unitPrice = res.data.price || child.unitPrice
        child.unitWeight = res.data.totalWeight || child.unitWeight
        child.kgPrice = (res.data.price || child.unitPrice) / (res.data.totalWeight || child.unitWeight || 1)
        child.map = res.data.detial || child.map
        
        // 重新计算该物料的总价和总重
        const quantity = Number(child.quantity) || 0
        child.totalPrice =  Number(child.unitPrice)
        child.totalWeight = Number(child.unitWeight)
        
        // 重新计算整体总价和总重
        calculateTotalPrice()
      }
    } catch (error) {
      console.error('重新计算物料价格失败:', error)
      // 如果计算失败，保持原有价格
      handleChildQuantityChange(index)
    }
  }
}

// 查询显示明细
const viewDetail = async (index: number) => {
  const detailData = formData.children[index].map as DetailData
  console.log('详情数据:', detailData)
  
  // 检查是否有详情数据
  if (!detailData || Object.keys(detailData).length === 0) {
    ElMessage.warning('该项目暂无详细费用明细数据')
    return
  }
  
  dialog.title = '费用详情'
  dialog.width = 700
  dialog.height = 350
  dialog.visible = true
  currentDetailData.value = detailData
}

// 颜色选择器相关
const showColorSelector = () => {
  if (props.mode === 'view') return // 查看模式不允许选择
  colorSelectorVisible.value = true
}

const handleColorSelect = (color: Color) => {
  selectedColor.value = color
  formData.color = color.colorName
  formData.colorPrice = 0
  // 颜色变化时重新计算总价
  if (formData.children && formData.children.length > 0) {
    calculateTotalPrice()
  }
}

// 项目选择器相关
const openProjectSelector = () => {
  if (props.mode === 'view') return // 查看模式不允许选择
  projectSelectorVisible.value = true
}

const handleProjectSelect = (project: ProjectDocument) => {
  selectedProject.value = project
  console.log('选择的项目:', project)
  formData.projectId = project.id
  formData.projectName = project.name
}

// 颜色档案配置
const colorSearchFields: Array<{
  label: string
  prop: string
  type: 'input' | 'select'
  options?: Array<{ label: string; value: any }>
}> = [
  { label: '颜色编码', prop: 'colorCode', type: 'input' },
  { label: '颜色名称', prop: 'colorName', type: 'input' },
  {
    label: '状态',
    prop: 'isActive',
    type: 'select',
    options: [
      { label: '启用', value: '0' },
      { label: '禁用', value: '1' },
    ],
  },
]

const colorTableColumns = [
  { prop: 'colorCode', label: '颜色编码', width: 120 },
  { prop: 'colorName', label: '颜色名称', width: 120 },
  { prop: 'description', label: '描述' },
]

// 项目状态映射
const statusOptions = [
  { value: 0, label: '进行中' },
  { value: 1, label: '已完成' },
  { value: 2, label: '已暂停' },
  { value: 3, label: '已取消' },
]

// 项目选择器搜索字段配置
const projectSearchFields = [
  { label: '项目名称', prop: 'name', type: 'input' as const },
  { label: '项目编号', prop: 'code', type: 'input' as const },
  { label: '客户名称', prop: 'customer', type: 'input' as const },
  {
    label: '项目状态',
    prop: 'status',
    type: 'select' as const,
    options: statusOptions,
  },
]

// 项目选择器表格列配置
const projectTableColumns = [
  { prop: 'name', label: '项目名称', width: 250 },
  { prop: 'code', label: '项目编号', width: 250 },
  { prop: 'customer', label: '客户名称', width: 250 },
  { prop: 'manager', label: '项目经理', width: 200 },
]

// API 封装
const getColorList = (params: any) => {
  return getColorListApi(params)
}

// 获取项目列表数据的API方法
const getProjectList = async (params: any) => {
  try {
    // 构建查询参数
    const queryParams: ProjectDocumentListParam = {
      name: params.name,
      code: params.code,
      customer: params.customer,
      status: params.status,
      page: params.page || 1,
      limit: params.limit || 10,
    }

    // 调用项目列表API - 使用真实API
    return await getProjectDocumentListApi(queryParams)
  } catch (error) {
    console.error('获取项目列表失败:', error)
    return { data: { list: [], total: 0 } }
  }
}

// 上移子物料
const moveUp = (index: number) => {
  if (index === 0) return
  
  // 交换数组元素位置
  const temp = formData.children[index]
  formData.children[index] = formData.children[index - 1]
  formData.children[index - 1] = temp
  
  // 重新计算总价（虽然顺序变化不影响计算，但为了保持一致性）
  calculateTotalPrice()
  
  console.log('上移物料，新顺序：', formData.children.map(item => item.name))
}

// 下移子物料
const moveDown = (index: number) => {
  if (index === formData.children.length - 1) return
  
  // 交换数组元素位置
  const temp = formData.children[index]
  formData.children[index] = formData.children[index + 1]
  formData.children[index + 1] = temp
  
  // 重新计算总价（虽然顺序变化不影响计算，但为了保持一致性）
  calculateTotalPrice()
  
  console.log('下移物料，新顺序：', formData.children.map(item => item.name))
}

// 简化的拖拽排序功能
const tableRef = ref()

// 拖拽状态
const dragState = reactive({
  isDragging: false,
  dragStartIndex: -1,
  dragOverIndex: -1
})

// 清理拖拽状态
const clearDragState = () => {
  Object.assign(dragState, {
    isDragging: false,
    dragStartIndex: -1,
    dragOverIndex: -1
  })
}

// 获取行样式，包含拖拽状态
const getRowStyle = ({ row, rowIndex }: { row: any, rowIndex: number }) => {
  const style: any = {
    cursor: props.mode === 'view' ? 'default' : 'grab'
  }
  
  // 添加拖拽状态样式
  if (dragState.isDragging && dragState.dragStartIndex === rowIndex) {
    style.opacity = 0.5
  }
  
  if (dragState.dragOverIndex === rowIndex && dragState.isDragging) {
    style.backgroundColor = '#f0f9ff'
  }
  
  return style
}

// 获取行类名
const getRowClassName = ({ row, rowIndex }: { row: any, rowIndex: number }) => {
  const classes = []
  
  if (dragState.isDragging && dragState.dragStartIndex === rowIndex) {
    classes.push('is-dragging')
  }
  
  if (dragState.dragOverIndex === rowIndex && dragState.isDragging) {
    classes.push('drag-over')
  }
  
  return classes.join(' ')
}

// 拖拽事件处理函数
const onDragStart = (index: number, event: DragEvent) => {
  if (props.mode === 'view') {
    event.preventDefault()
    return
  }
  
  dragState.isDragging = true
  dragState.dragStartIndex = index
  
  event.dataTransfer!.effectAllowed = 'move'
  event.dataTransfer!.setData('text/plain', index.toString())
  
  console.log('开始拖拽行:', index, formData.children[index]?.name)
}



const onDragOver = (event: DragEvent) => {
  event.preventDefault()
  if (dragState.isDragging) {
    event.dataTransfer!.dropEffect = 'move'
  }
}



const onDragEnd = () => {
  console.log('拖拽结束')
  clearDragState()
}

// 简化的拖拽初始化，添加行级别事件监听
const initTableDragEvents = () => {
  if (props.mode === 'view') return
  
  nextTick(() => {
    const table = tableRef.value?.$el
    if (!table) return
    
    const tbody = table.querySelector('tbody')
    if (!tbody) return
    
    // 为所有表格行添加拖拽事件监听
    const rows = tbody.querySelectorAll('tr')
    rows.forEach((row: HTMLElement, index: number) => {
      // 存储行索引在 dataset 中
      row.dataset.rowIndex = index.toString()
      
      // 移除现有的事件监听器（如果有的话）
      const oldDragEnter = row.getAttribute('data-dragenter-handler')
      if (oldDragEnter) {
        row.removeEventListener('dragenter', (window as any)[oldDragEnter])
      }
      
      // 添加新的事件监听器
      row.addEventListener('dragenter', handleRowDragEnter)
      row.addEventListener('dragleave', handleRowDragLeave)
      row.addEventListener('dragover', handleRowDragOver)
      row.addEventListener('drop', handleRowDrop)
    })
    
    console.log('拖拽功能已启用，绑定了', rows.length, '行')
  })
}

// 行级别拖拽事件处理函数
const handleRowDragEnter = (event: DragEvent) => {
  const currentRow = event.currentTarget as HTMLElement
  const index = parseInt(currentRow.dataset.rowIndex || '-1')
  
  if (!dragState.isDragging || dragState.dragStartIndex === index) return
  event.preventDefault()
  dragState.dragOverIndex = index
  console.log('拖拽进入行:', index)
}

const handleRowDragLeave = (event: DragEvent) => {
  // 避免在同一行内部移动时清除状态
  const related = event.relatedTarget as HTMLElement
  const currentRow = event.currentTarget as HTMLElement
  if (related && currentRow && currentRow.contains(related)) {
    return
  }
  dragState.dragOverIndex = -1
}

const handleRowDragOver = (event: DragEvent) => {
  if (!dragState.isDragging) return
  event.preventDefault()
  event.dataTransfer!.dropEffect = 'move'
}

const handleRowDrop = (event: DragEvent) => {
  event.preventDefault()
  
  const currentRow = event.currentTarget as HTMLElement
  const index = parseInt(currentRow.dataset.rowIndex || '-1')
  
  if (!dragState.isDragging || 
      dragState.dragStartIndex === -1 || 
      dragState.dragStartIndex === index) {
    clearDragState()
    return
  }
  
  const sourceIndex = dragState.dragStartIndex
  console.log('执行排序:', { from: sourceIndex, to: index })
  
  // 执行数据移动
  const item = formData.children[sourceIndex]
  formData.children.splice(sourceIndex, 1)
  
  const actualTargetIndex = sourceIndex < index ? index - 1 : index
  formData.children.splice(actualTargetIndex, 0, item)
  
  // 重新计算总价
  calculateTotalPrice()
  
  clearDragState()
  console.log('排序完成，新顺序：', formData.children.map(item => item.name))
}



// 简化的拖拽初始化
const safeDragInit = async () => {
  if (props.mode === 'view') return
  initTableDragEvents()
}

// 监听children变化，重新初始化拖拽事件 - 优化版本
watch(
  () => formData.children.length,
  (newLength, oldLength) => {
    // 避免不必要的重新初始化
    if (newLength === 0 || props.mode === 'view') return
    
    // 只在真正发生变化时才重新初始化
    if (newLength !== oldLength) {
      console.log('表格行数变化，重新初始化拖拽:', { from: oldLength, to: newLength })
      
      // 清理可能存在的旧状态
      clearDragState()
      
      // 延迟执行，确保DOM完全更新
      setTimeout(async () => {
        try {
          await safeDragInit()
        } catch (error) {
          console.error('Watch触发的拖拽初始化失败:', error)
        }
      }, 200)
    }
  },
  { immediate: false }
)

// 加载默认颜色（新增模式下自动设置第一个颜色）
const loadDefaultColor = async () => {
  if (props.mode === 'add' && !formData.color) {
    try {
      const res = await getColorListApi({
        colorCode: '',
        colorName: '',
        isActive: 0, // 只获取启用的颜色
        page: 1,
        limit: 1
      })
      if (res && res.data && res.data.list && res.data.list.length > 0) {
        const firstColor = res.data.list[0]
        formData.color = firstColor.colorName
        selectedColor.value = firstColor
        console.log('自动设置默认颜色:', firstColor.colorName)
      }
    } catch (error) {
      console.error('加载默认颜色失败:', error)
    }
  }
}

// 生命周期钩子
onMounted(() => {
  loadProjectList()
  // 新增模式下加载默认颜色
  loadDefaultColor()
  
  // 初始化拖拽事件
  if (formData.children.length > 0 && props.mode !== 'view') {
    setTimeout(async () => {
      await safeDragInit()
    }, 500)
  }
})

// 组件卸载时清理拖拽相关资源
onBeforeUnmount(() => {
  console.log('组件即将卸载，清理拖拽资源')
  
  // 清理拖拽状态
  clearDragState()
  
  // 清理计算总价的定时器
  if (calculateTotalPriceTimeout) {
    clearTimeout(calculateTotalPriceTimeout)
    calculateTotalPriceTimeout = null
    console.log('已清理计算总价定时器')
  }
  
  // 清理所有拖拽相关的DOM事件
  try {
    const tbody = document.querySelector('.sortable-table tbody')
    if (tbody) {
      const draggableRows = tbody.querySelectorAll('tr[draggable]')
      draggableRows.forEach((row: any) => {
        try {
          row.draggable = false
          row.removeAttribute('data-index')
          row.classList.remove('dragging', 'drag-over', 'draggable-row')
          row.style.cursor = ''
          
          // 移除所有可能的拖拽相关事件监听器
          const newRow = row.cloneNode(true)
          if (row.parentNode && row.parentNode.contains(row)) {
            row.parentNode.replaceChild(newRow, row)
          }
        } catch (rowError) {
          console.warn('清理单行拖拽事件失败:', rowError)
        }
      })
    }
  } catch (error) {
    console.warn('清理拖拽事件失败:', error)
  }
})
</script>

<template>
  <div class="bom-form">
    <div class="form-header">
      <h3>{{ mode === 'add' ? '新增非标结构件' : mode === 'edit' ? '编辑非标结构件' : '非标结构件详情' }}</h3>
    </div>

    <el-form ref="formRef"
             :model="formData"
             label-width="90px"
             :rules="rules">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="名称" prop="name">
            <el-input v-model="formData.name"
                      placeholder="请输入名称"
                      :disabled="mode === 'view'" />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="规格" prop="specification">
            <el-input v-model="formData.specification"
                      placeholder="请输入规格"
                      :disabled="mode === 'view'" />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="宽度" prop="width">
            <el-input v-model="formData.width"
                      :disabled="mode === 'view'">
              <template #append>mm</template>
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="高度" prop="height">
            <el-input v-model="formData.height"
                      :disabled="mode === 'view'">
              <template #append>mm</template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="材质" prop="material">
            <el-input v-model="formData.material"
                      :disabled="mode === 'view'" />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="数量" prop="quantity">
            <el-input-number v-model="formData.quantity"
                             style="width: 260px"
                             :min="1"
                             :precision="0"
                             :disabled="mode === 'view'" />
          </el-form-item>
        </el-col>
        
        <el-col :span="6">
          <el-form-item label="单位" prop="unit">
            <el-input v-model="formData.unit"
                      :disabled="mode === 'view'" />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="颜色" prop="color">
            <el-input v-model="formData.color"
                      placeholder="请选择颜色"
                      readonly>
              <template #append>
                <el-button @click="showColorSelector" :disabled="mode === 'view'">选择</el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="含税单价" prop="unitPrice">
            <el-input :value="formatPrice(formData.unitPrice)"
                      readonly />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="单重" prop="unitWeight">
            <el-input :value="formatNumber(formData.unitWeight)"
                      readonly />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="公斤价" prop="kgPrice">
            <el-input :value="formatPrice(formData.kgPrice)"
                      readonly />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="总重" prop="totalWeight">
            <el-input :value="formatNumber(formData.totalWeight)"
                      readonly />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="项目" prop="projectId">
            <el-input :model-value="selectedProject ? selectedProject.name : ''"
                      placeholder="请选择项目"
                      readonly>
              <template #append>
                <el-button @click="openProjectSelector" :disabled="mode === 'view'">选择</el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        
        <el-col :span="6">
          <el-form-item label="颜色价格"
                        v-if="formData.color!='标准色' && formData.color">
            <el-input type="number"
                      v-model="formData.colorPrice"
                      placeholder="请输入颜色价格"
                      :disabled="mode === 'view'">
            </el-input>
          </el-form-item>
        </el-col>
        
        <el-col :span="6">
          <el-form-item label="包装费系数">
            <el-input type="number"
                      v-model="formData.packingPriceCoefficient"
                      placeholder="请输入包装费系数"
                      :disabled="mode === 'view'"
                      @blur="calculateFinalPrice">
              <template #append>元/kg</template>
            </el-input>
          </el-form-item>
        </el-col>
        
        <el-col :span="6">
          <el-form-item label="总价" prop="totalPrice">
            <el-input :value="formatPrice(formData.totalPrice)"
                      readonly />
          </el-form-item>
        </el-col>
      </el-row>
      
  

      <!-- 分摊费用部分 -->
      <div v-if="mode == 'view'" class="share-section">
        <div class="share-title">
          <el-divider content-position="left">
            <el-icon>
              <Money />
            </el-icon>
            <span>分摊费用</span>
          </el-divider>
        </div>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="包装费">
              <el-input :value="formatPrice(currentPackingFee)"
                        readonly>
                <template #append>
                  <span class="unit">元</span>
                </template>
                <template #prefix>
                  <el-icon>
                    <Box />
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="运输费">
              <el-input :value="formatPrice(formData.transportationPrice)"
                        readonly>
                <template #append>
                  <span class="unit">元</span>
                </template>
                <template #prefix>
                  <el-icon>
                    <Van />
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="实施费">
              <el-input :value="formatPrice(formData.implementationPrice)"
                        readonly>
                <template #append>
                  <span class="unit">元</span>
                </template>
                <template #prefix>
                  <el-icon>
                    <SetUp />
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="其他费用">
              <el-input :value="formatPrice(formData.otherPrice)"
                        readonly>
                <template #append>
                  <span class="unit">元</span>
                </template>
                <template #prefix>
                  <el-icon>
                    <More />
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 使用tabs替换原来的两个表格 -->
      <el-tabs v-model="activeTab">
        <!-- 物料清单tab -->
        <el-tab-pane label="物料清单" name="materials">
          <div style="margin-bottom: 16px;">
            <el-button
              v-if="mode !== 'view'"
              type="primary"
              size="small"
              @click="openMaterialSelector"
            >
              <el-icon><Plus /></el-icon>
              添加物料
            </el-button>
          </div>
          
          <el-form-item prop="bomMaterialDtoList">
            <el-table ref="tableRef"
                      :data="formData.children"
                      border
                      style="width: 100%"
                      row-key="tempId"
                      :class="{ 'sortable-table': mode !== 'view' }"
                      :row-class-name="getRowClassName"
                      :row-style="getRowStyle"
                      >
              <el-table-column v-if="mode !== 'view'"
                               label="拖拽"
                               width="60"
                               align="center">
                <template #default="{ $index }">
                  <div 
                    class="drag-handle" 
                    style="cursor: move; color: #909399; padding: 5px;"
                    draggable="true"
                    @dragstart="onDragStart($index, $event)"
                    @dragend="onDragEnd"
                  >
                    <el-icon>
                      <DCaret />
                    </el-icon>
                  </div>
                </template>
              </el-table-column>
              <el-table-column type="index"
                               label="序号"
                               width="70">
                <template #default="{ $index }">
                  {{ $index + 1 }}
                </template>
              </el-table-column>
              <el-table-column prop="name"
                               label="名称"
                               min-width="120">
                <template #default="{ row, $index }">
                  {{ row.name }}
                </template>
              </el-table-column>
              <el-table-column prop="specification"
                               label="型号"
                               min-width="120" />
              <el-table-column prop="material"
                               label="材质"
                               min-width="100" />
              <el-table-column prop="height"
                               label="高度"
                               min-width="100">
                <template #default="scope">
                  <el-input
                    v-if="mode !== 'view'"
                    v-model="scope.row.height"
                    :min="0"
                    size="small"
                    style="width: 80px"
                    @change="() => handleChildHeightChange(scope.$index)"
                  />
                  <span v-else>{{ formatNumber(scope.row.height) }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="width"
                               label="宽度"
                               min-width="100">
                <template #default="scope">
                  <el-input
                    v-if="mode !== 'view'"
                    v-model="scope.row.width"
                    :min="0"
                    size="small"
                    style="width: 80px"
                    @change="() => handleChildHeightChange(scope.$index)"
                  />
                  <span v-else>{{ formatNumber(scope.row.width) }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="quantity"
                               label="数量"
                               width="120">
                <template #default="scope">
                  <el-input
                    v-if="mode !== 'view'"
                    v-model="scope.row.quantity"
                    :min="1"
                    size="small"
                    style="width: 80px"
                    @change="() => handleChildQuantityChange(scope.$index)"
                  />
                  <span v-else>{{ formatNumber(scope.row.quantity) }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="unitPrice"
                               label="含税单价"
                               min-width="100">
                <template #default="scope">
                  {{ formatPrice(scope.row.unitPrice) }}
                </template>
              </el-table-column>
           
              <el-table-column prop="unitWeight"
                               label="单重"
                               min-width="100">
                <template #default="scope">
                  {{ formatNumber(scope.row.unitWeight) }}
                </template>
              </el-table-column>

              <el-table-column label="操作"
                               width="180">
                <template #default="scope">
                  <el-button type="primary"
                             link
                             @click="viewDetail(scope.$index)"
                             size="small"
                             title="查看详情">
                    <el-icon><View /></el-icon>
                  </el-button>
                  <el-button v-if="mode !== 'view'"
                             type="success"
                             link
                             @click="moveUp(scope.$index)"
                             :disabled="scope.$index === 0"
                             size="small"
                             title="上移">
                    <el-icon><ArrowUp /></el-icon>
                  </el-button>
                  <el-button v-if="mode !== 'view'"
                             type="success"
                             link
                             @click="moveDown(scope.$index)"
                             :disabled="scope.$index === formData.children.length - 1"
                             size="small"
                             title="下移">
                    <el-icon><ArrowDown /></el-icon>
                  </el-button>
                  <el-button v-if="mode !== 'view'"
                             type="danger"
                             link
                             @click="removeChild(scope.$index)"
                             size="small"
                             title="删除">
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-tab-pane>
      </el-tabs>

      <el-form-item label="备注">
        <el-input v-model="formData.remark"
                  type="textarea"
                  :rows="3"
                  :disabled="mode === 'view'"
                  placeholder="输入描述" />
      </el-form-item>
    </el-form>

    <div class="form-actions">
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary"
                 @click="submitForm"
                 v-if="mode !== 'view'">保存
      </el-button>
      <el-button type="success" @click="printPage">打印</el-button>
    </div>

    <!-- 颜色选择器（单选） -->
    <ArchiveSelector v-model="colorSelectorVisible"
                     title="选择颜色"
                     :search-fields="colorSearchFields"
                     :table-columns="colorTableColumns"
                     :fetch-data-api="getColorList"
                     :multiple="false"
                     :disabled="mode === 'view'"
                     @confirm="handleColorSelect" />

    <!-- 项目选择器组件 -->
    <ArchiveSelector v-model="projectSelectorVisible"
                     title="选择项目"
                     :search-fields="projectSearchFields"
                     :table-columns="projectTableColumns"
                     :fetch-data-api="getProjectList"
                     :multiple="false"
                     :disabled="mode === 'view'"
                     @confirm="handleProjectSelect" />

    <!-- 物料选择对话框 -->
    <MaterialDialog
      ref="materialDialogRef"
      :multiple="true"
      @handleMaterialSelectionChange="handleMaterialSelectionChange"
      @confirmMaterialSelect="confirmMaterialSelect"
    />

    <!-- 详情 -->
    <sys-dialog :title="dialog.title"
                :width="dialog.width"
                :visible="dialog.visible"
                :height="dialog.height"
                @onClose="onClose"
                @onConfirm="onClose">
      <template #content>
        <div class="detail-container"
             v-if="currentDetailData">
          <el-descriptions :column="2"
                           border>
            <template v-for="(value, key) in currentDetailData"
                      :key="key">
              <el-descriptions-item :label="(key as string).replace(/@/g, '')">
                {{ value }}
                <!-- 价格相关单位 -->
                <template v-if="(key as string).includes('总价') || (key as string).includes('费用')|| (key as string).includes('单价')">
                  <span class="unit">元</span>
                </template>
                
                <!-- 重量相关单位 -->
                <template v-else-if="(key as string).includes('总重') || (key as string).includes('单重')">
                  <span class="unit">kg</span>
                </template>
                
                <!-- 面积相关单位 -->
                <template v-else-if="(key as string).includes('单面积') || (key as string).includes('总面积')">
                  <span class="unit">m²</span>
                </template>

                <!-- 加工工艺单位 -->
                <template v-else-if="(key as string).includes('自动冲压') && !(key as string).includes('冲压')">
                  <span class="unit">元/kg</span>
                </template>
                <template v-else-if="(key as string).includes('冲压') || 
                                    (key as string).includes('钻孔') || 
                                    (key as string).includes('折弯') || 
                                    (key as string).includes('焊接') || 
                                    (key as string).includes('板材下料')">
                  <span class="unit">元/件</span>
                </template>
                <template v-else-if="(key as string).includes('辊轧成型') || 
                               (key as string).includes('切管下料') || 
                               (key as string).includes('抛丸')">
                  <span class="unit">元/kg</span>
                </template>
                <template v-else-if="(key as string).includes('激光下料')|| 
                               (key as string).includes('喷涂')">
                  <span class="unit">元/m</span>
                </template>
                <template v-else-if="(key as string).includes('剪板下料')">
                  <span class="unit">元/次</span>
                </template>
                <template v-else-if="(key as string).includes('长度') || (key as string).includes('厚度')">
                  <span class="unit">mm</span>
                </template>
                <template v-else-if="(key as string).includes('厚度')">
                  <span class="unit">m</span>
                </template>
              </el-descriptions-item>
            </template>
          </el-descriptions>
        </div>
      </template>
    </sys-dialog>
  </div>
</template>

<style scoped lang="scss">
@media print {
  .form-actions,
  .el-button,
  .el-tabs__header,
  .el-form-item__label {
    display: none !important;
  }
  /* 隐藏菜单栏 */
  .sidebar {
    display: none !important;
  }

  /* 隐藏页签 */
  .tabs {
    display: none !important;
  }

  /* 隐藏其他不需要的元素，例如标签栏 */
  .el-tabs__header {
    display: none !important;
  }

  .el-table {
    width: 100% !important;
    border-collapse: collapse;
  }

  .el-table th,
  .el-table td {
    border: 1px solid #000;
    padding: 8px;
  }

  .el-icon,
  .unit {
    display: none;
  }

  .bom-form {
    width: 100%;
    margin: 0;
    padding: 0;
  }
}

.bom-form {
  padding: 20px;
  padding-top: 0;
  background: #fff;
  height: 100%;
  overflow-y: auto;

  .form-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 1px solid #eee;

    h3 {
      margin: 0;
      font-size: 18px;
    }
  }

  .form-actions {
    display: flex;
    justify-content: center;
    margin-top: 30px;
  }

  // 修改禁用状态下的样式
  :deep(.el-input.is-disabled .el-input__wrapper) {
    background-color: var(
      --el-input-disabled-bg-color,
      var(--el-disabled-bg-color)
    );
  }

  :deep(.el-input.is-disabled .el-input__inner) {
    color: var(--el-text-color-primary);
    -webkit-text-fill-color: var(--el-text-color-primary);
  }

  :deep(.el-textarea.is-disabled .el-textarea__inner) {
    color: var(--el-text-color-primary);
    -webkit-text-fill-color: var(--el-text-color-primary);
  }

  :deep(.el-radio.is-disabled.is-checked) {
    .el-radio__label {
      color: var(--el-text-color-primary);
    }
  }

  :deep(.el-radio.is-disabled) {
    .el-radio__label {
      color: var(--el-text-color-primary);
    }
  }

  // 添加价格输入样式
  :deep(.el-input-group__append) {
    padding: 0 10px;
    background-color: var(--el-color-primary-light-8);
    color: var(--el-color-primary);
    font-weight: bold;
  }

  // 添加tabs相关样式
  :deep(.el-tabs__header) {
    margin-bottom: 15px;
  }

  :deep(.el-tabs__nav-wrap::after) {
    height: 1px;
  }

  :deep(.el-tabs__item) {
    font-size: 14px;
    height: 40px;
    line-height: 40px;
  }

  :deep(.el-tabs__item.is-active) {
    font-weight: bold;
  }
}

.share-section {
  margin-top: 20px;
  padding: 0 10px;

  .share-title {
    margin-bottom: 20px;

    .el-divider {
      .el-icon {
        margin-right: 8px;
        color: var(--el-color-primary);
      }

      span {
        font-size: 16px;
        font-weight: bold;
        color: var(--el-text-color-primary);
      }
    }
  }

  :deep(.el-form-item) {
    margin-bottom: 22px;

    .el-form-item__label {
      font-weight: bold;
      color: var(--el-text-color-regular);
    }

    .el-input {
      .el-input__wrapper {
        background-color: var(--el-fill-color-blank);
      }

      .el-input__prefix {
        color: var(--el-color-primary);
        margin-right: 8px;
      }

      .el-input__inner {
        color: var(--el-color-danger);
        font-weight: bold;
        text-align: right;
      }

      .el-input-group__append {
        padding: 0 12px;
        background-color: var(--el-color-primary-light-8);

        .unit {
          color: var(--el-color-primary);
          font-size: 13px;
          font-weight: bold;
        }
      }
    }
  }
}

// 表格样式
.el-table {
  .el-table__header-wrapper th {
    background-color: #DCDCDC;
    border-bottom: 1px solid #8B8B7A;
    border-right: 1px solid #8B8B7A;
  }
}

// 禁用数字输入框箭头
input::-webkit-inner-spin-button,
input::-webkit-outer-spin-button {
  -webkit-appearance: none !important;
}

.detail-container {
  padding: 20px;

  :deep(.el-descriptions) {
    margin-bottom: 20px;

    .el-descriptions__header {
      margin-bottom: 20px;
    }

    .el-descriptions__label {
      font-weight: bold;
      color: var(--el-text-color-primary);
      background-color: var(--el-fill-color-light);
      min-width: 150px;
    }

    .el-descriptions__content {
      font-size: 14px;
      color: var(--el-text-color-regular);

      .unit {
        margin-left: 4px;
        font-size: 12px;
        color: var(--el-text-color-secondary);
      }
    }
  }
}

// 拖拽排序样式 - 优化版本
.sortable-table {
  :deep(.el-table__body tbody) {
    tr[draggable="true"] {
      cursor: grab;
      transition: all 0.2s ease;
      position: relative;
      
      &:hover {
        background-color: rgba(64, 158, 255, 0.05);
        transform: translateY(-1px);
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        
        .drag-handle {
          color: var(--el-color-primary) !important;
          transform: scale(1.1);
        }
      }
      
      &.dragging {
        opacity: 0.7;
        background-color: var(--el-color-primary-light-9);
        border: 2px dashed var(--el-color-primary);
        transform: scale(1.02);
        box-shadow: 0 6px 16px rgba(64, 158, 255, 0.3);
        z-index: 1000;
        cursor: grabbing;
      }
      
      &.drag-over {
        background-color: var(--el-color-primary-light-8);
        border: 2px solid var(--el-color-primary);
        border-radius: 4px;
        transform: translateY(-2px);
        animation: dragPulse 0.8s ease-in-out infinite alternate;
      }
      
      &:active {
        cursor: grabbing;
      }
    }
  }
}

// 拖拽脉冲动画
@keyframes dragPulse {
  from {
    border-color: var(--el-color-primary);
    box-shadow: 0 0 0 0 rgba(64, 158, 255, 0.4);
  }
  to {
    border-color: var(--el-color-success);
    box-shadow: 0 0 0 4px rgba(64, 158, 255, 0.1);
  }
}

// 拖拽手柄样式
.drag-handle {
  cursor: grab;
  color: #C0C4CC;
  transition: all 0.2s ease;
  
  border-radius: 3px;
  font-size: 16px;
  
  &:hover {
    color: var(--el-color-primary);
    background-color: rgba(64, 158, 255, 0.1);
    transform: scale(1.1);
  }
  
  &:active {
    cursor: grabbing;
    color: var(--el-color-success);
  }
}

// 排序按钮优化
.sort-buttons {
  display: flex;
  flex-direction: column;
  gap: 2px;
  
  .sort-btn {
    padding: 2px 6px;
    font-size: 12px;
    min-height: 22px;
    line-height: 1;
    border-radius: 3px;
    transition: all 0.2s ease;
    
    &:not(:disabled):hover {
      transform: scale(1.05);
    }
    
    &:disabled {
      opacity: 0.3;
      cursor: not-allowed;
      transform: none;
    }
  }
}

// 禁用拖拽时的样式
.sortable-table.disabled {
  :deep(.drag-handle) {
    cursor: not-allowed;
    color: #c0c4cc;
    opacity: 0.5;
  }
  
  :deep(tr[draggable="true"]) {
    cursor: not-allowed;
    
    &:hover {
      transform: none;
      box-shadow: none;
      background-color: transparent;
    }
  }

  // 拖拽相关样式
  .sortable-table {
    .is-dragging {
      opacity: 0.5;
    }
    
    .drag-over {
      background-color: #f0f9ff !important;
      border-left: 3px solid #409eff !important;
    }
  }

  .drag-handle {
    cursor: move !important;
    color: #909399;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 5px;
    border-radius: 4px;
    transition: all 0.2s ease;
    
    &:hover {
      color: #409eff;
      background-color: #f5f7fa;
    }
    
    &:active {
      background-color: #e6f7ff;
    }
  }

  // Element Plus 表格行样式
  :deep(.el-table .el-table__row) {
    transition: background-color 0.2s ease;
    
    &.is-dragging {
      opacity: 0.5;
      background-color: #f8f9fa !important;
    }
    
    &.drag-over {
      background-color: #f0f9ff !important;
      box-shadow: inset 0 0 0 2px #409eff;
    }
  }
}
</style> 